/**
 * @description: 定义班级 service
 * @version: 0.0.1
 * @author: z..
 * @Date: 2023-06-12 18:16:39
 */

import { Provide } from '@midwayjs/core';
import { AppConfig } from './app_config.entity';

import { InjectRepository, InjectDataSource } from '@midwayjs/sequelize';
import { Repository, Sequelize } from 'sequelize-typescript';

@Provide()
export class AppConfigModel {

  @InjectRepository(AppConfig)
  AppConfigRepository: Repository<AppConfig>;

  @InjectDataSource()
  SequelizeQuery: Sequelize

  /**
   * 新增应用token数据
   * @param {*} id 
   * @param {*} accessToken 
   * @param {*} expiresTime
   * @returns 
   */
  async insertAppInfo(params: any): Promise<any> {
    let sql = `INSERT INTO app_config 
        SET app_name = '${params.appName}',
            app_key = '${params.appKey}',
            app_secret = '${params.appSecret}',
            access_token = '${params.accessToken}',
            expires_time = '${params.expiresTime}',
            created_at = now(),
            updated_at = now();`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }
  /**
   * 根据appkey查询应用token
   * @param {*} appKey 
   * @returns 
   */
  async getDataByAppkey(appKey: string): Promise<object> {
    const sql = `SELECT id,access_token,expires_time FROM app_config WHERE app_key = '${appKey}';`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  };

  /**
    * 根据id更新应用token数据
    * @param {*} param0.id 
    * @param {*} param0.accessToken 
    * @param {*} param0.expiresTime
    * @returns 
    */
  async updateTokenById({ accessToken, expiresTime, id }: { accessToken: string, expiresTime: number, id: number }): Promise<any> {
    const sql = `UPDATE app_config 
        SET access_token = '${accessToken}',
            expires_time = '${expiresTime}',
            updated_at = now()
        WHERE
            id = ${id}`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

}